<%@page contentType="text/html" import="java.sql.*,java.text.*,java.util.*,merlin.beans.*,merlin.dao.*,merlin.managers.*,merlin.utils.*" %>

<!--
	Name		: Report Download Confirmation Page.
	Developed By: Sandip Bhattacharya (sandipkb@yahoo.com)
	Version 	: 1.0
-->
<%
	// let the user access the system only if he is logged in.
	if(session.getAttribute("IWusername") == null){
		response.sendRedirect("IndustryWatchLogin.jsp");
		return;
	}

	// check 2 : see if the user has agreed to the licence agreement or not.
  	IWCustomerDetailsBean bean = (IWCustomerDetailsBean)session.getAttribute("IWUserDetails");

  	if(bean.getLicenceAcceptanceDate() == null){
  		response.sendRedirect("iwLicenceAgreement.jsp");
		return;
  	}

	// additional check : the user cannot be a demo user.
  	if(bean.isTrialIndicator()){
  		RequestDispatcher disp = request.getRequestDispatcher("iwMainPageDemoVersion.jsp");
  		disp.forward(request,response);
  		return;
  	}

	DbResultSet result = null;
	int pdfCredits = 0;
	String subscriptionType = null;
	String confirmMessage = null;
	String buttonMessage = null;
	String singleSectorReportPrice = null;
	String currentMonth = null;

	// The sectors selected.
	String sectorIds = request.getParameter("sectorids");

	if(sectorIds != null && ! sectorIds.equals("")){
		result = ReportTitlesManager.selectReportTitlesRecords("REPORT_TITLES_ID IN (" + sectorIds + ")","REPORT_TITLE ASC");

	  	// get the current month.
	  	currentMonth = new DateFormatSymbols().getMonths()[new java.util.Date().getMonth()];

		HashMap mapConfigs = MsalResearchersManager.getAllConfigurationDetails();

		DecimalFormat fmt = new DecimalFormat("####.##");
		singleSectorReportPrice = fmt.format(Double.parseDouble((String)mapConfigs.get(ApplicationResources.getInstance().getProperty("IndustryWatchSinglePDF"))));

		pdfCredits = IndustryWatchManager.getAvailablePDFCredits(bean.getEmailAddress());
		subscriptionType = bean.getSubscriptionType();


		if("A".equals(subscriptionType) || "C".equals(subscriptionType)){
			confirmMessage = "I wish to purchase the reports that I have selected using my credit card";
			buttonMessage = "Your Details";
		}else{
			confirmMessage = "I wish to receive the full industry reports as detailed above.";
			buttonMessage = "Send Reports Now";
		}
	}
%>

<HTML>
	<HEAD>
	    <TITLE>Download full reports</TITLE>

		<!-- begin Prototype import -->
		<script type='text/javascript' src='mr_scripts/prototype.js'></script>
		<!-- ends Prototype import -->

		<!-- begin imports for sorting of the table -->
        <script type="text/javascript" src="mr_scripts/sorttable.js"></script>
        <style>
			.sortablecolumn {
				cursor: pointer;
				cursor: hand;
			}
        </style>
		<!-- ends imports for sorting of the table -->

		<%
			if(sectorIds != null && ! sectorIds.equals("")){
		%>
	    <script>
	    	var pdfCredits			= <%=pdfCredits%>;
	    	var subscriptionType	= '<%=subscriptionType%>';
	    	var singleReportCost	= <%=singleSectorReportPrice%>;
			var cost				= 0;

	    	function calculatePrice(frm){
	    		if(pdfCredits < frm.selReports.length){
					cost = ((frm.selReports.length - pdfCredits) * singleReportCost).toFixed(2);
					$("spnCost").innerHTML = ' Total Cost : &pound;' + cost;
					$("spnCost").show();
					if(subscriptionType=='B')$("spnNote").show();
	    		}else{
	    			$("spnCost").hide();
	    			if(subscriptionType=='B')$("spnNote").hide();
	    		}
	    	}

	    	function removeSelectedItem(frm){
	    		for(var r = frm.selReports.length - 1; r >=0;r--){
	    			if(frm.selReports.options[r].selected){
	    				frm.selReports.remove(r);
	    			}
	    		}
	    		calculatePrice(frm);
	    	}

	    	function sendReports(frm){
	    		if(!frm.chkConfirm.checked){
	    			alert("You must select the checkbox first");
	    			return;
	    		}
	    		if(frm.selReports.length == 0){
	    			alert("There is no report to download");
	    			return;
	    		}

	    		var selIds = "";
	    		for(var r = 0; r < frm.selReports.length;r++){
	    			selIds = selIds + "," + frm.selReports.options[r].value;
	    		}
	    		if(selIds.length > 0)selIds = selIds.substring(1);
       			frm.hidReportIds.value = selIds;
	    		if(cost > 0){
	    			// send to credit card details page, Type A users will always go this way.Type B sometimes, if thety are overpurchasing.
	    			frm.numReportsToPurchase.value = frm.selReports.length - pdfCredits;
	    			frm.txtInvoiceTotal.value = cost;
					frm.mode.value = "buyPdfCredits";
					frm.submit();
	    		}else{
	    			// send to report link generation code.Type B users.
	    			frm.mode.value = "generateReportDownload";
	    			frm.submit();
	    		}
	    	}
	    </script>
		<%
			}
		%>

		<script>
	    	function downloadReport(uuid){
	    		document.location = "industryWatch?mode=pdfReportDownload&downloadId=" + uuid;
	    	}

			function logoutIWUser(frm){
				frm.mode.value	= "logoutFromIndustryWatch";
				frm.action		= "industryWatch";
				frm.target		= "_top";
				frm.submit();
			}
		</script>
	    <style type="text/css">
	    	th{
	    		border-style: none none solid none;
				border-width:1px;
	    	}
	    </style>
		<link href="css/master.css" rel="stylesheet" type="text/css">
	</HEAD>
	<BODY>
		<div align="center">
			<table width="800px" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td height="20" colspan="2" class="topnav">
						<ul>
							<li><a style="font-size:9px" href="industryWatch?mode=logoutFromIndustryWatch">:: Log Out&nbsp;&nbsp;&nbsp;</a></li>
							<li><a style="font-size:9px" href='iwMainPage.jsp'>: Return to Industry Watch</a></li>
						</ul>
					</td>
				</tr>
				<tr>
					<td height="120" colspan="2" background="mr_images/IndustryWatchHeader.jpg">&nbsp;</td>
				</tr>
			</table>
		</div>
		<table width="800" align="center">
			<%
				if(sectorIds != null && ! sectorIds.equals("")){
			%>
			<tr>
				<td>
					<p>
					<%
						if("A".equals(subscriptionType) || "C".equals(subscriptionType)){

					%>
							You have requested the <%=currentMonth%> edition of each full report listed below. The Ebook version of the report costs &pound;<%=singleSectorReportPrice%> (inc VAT) <br>
							per title. To proceed with this order tick the box below and the cost will be charged to credit card details you will be asked to provide
					<%
						}else{
					%>
							You have requested the <%=currentMonth%> edition of each full report listed below. Your subscription allows the download of <%= pdfCredits%> reports on demand.<br>
							Please confirm you wish to proceed.

							<span id="spnNote">
								<br><br>
								<b>Note : </b>You have selected more reports than the number of report downloads available to you. You can purchase the additional reports at &pound;<%=singleSectorReportPrice%> (inc VAT) per report , or
								you can remove extra reports from the list.
							</span>
					<%
						}
					%>
						<p>
						<div style="height:8px"><span id="spnCost" style="font: 11px verdana,arial, sans-serif ;"></span></div>
						<p>
						<form name="frm" action="merlin" method="post">
							<input type="hidden" name="hidReportIds">
							<input type="hidden" name="mode">
							<input type="hidden" name="numReportsToPurchase" value="0">
							<input type="hidden" name="txtInvoiceTotal">

							<input type="hidden" name="hidEmailAddress" value="<%=bean.getEmailAddress()%>">

							<table>
								<tr>
									<td>
										<select name="selReports" size="5" style="width: 250px;font: 11px verdana,arial, sans-serif ;">
											<%
												for(int i=0;i< result.size();i++){
													ReportTitlesBean rtb = (ReportTitlesBean)result.get(i);
													out.println("<option value='" + rtb.getReportTitlesId() + "'>" + rtb.getReportTitle() + "</option>");
												}
											%>
										</select>
									</td>
									<td style="vertical-align:bottom">
										&nbsp;&nbsp;<input type="button" style="font: 11px verdana,arial, sans-serif ;" value="Remove Selected" onclick="removeSelectedItem(document.frm)">
									</td>
								</tr>
							</table>
							<p>
							<input type="checkbox" name="chkConfirm"><%=confirmMessage%><p>
							<input type="button" style="font: 11px verdana,arial, sans-serif ;" value="Cancel" onclick="document.location.href='iwMainPage.jsp'">
							<input type="button" style="font: 11px verdana,arial, sans-serif ;" value="<%=buttonMessage%>" onclick="sendReports(document.frm)">
						</form>
				</td>
			</tr>
			<%
				}
			%>

			<%
				PDFDownloadDetailsBean[] arrDownloads = IndustryWatchManager.getPDFDownloadDetailsByCustomerId(bean.getCustomerDetailsId());
				if(arrDownloads != null && arrDownloads.length > 0){
			%>
			<tr>
				<td>
					<p>
					<table class="sortable" width='100%' cellspacing='0' cellpadding = '5' style="border-style: solid;border-width: 1px;font:11px verdana,arial, sans-serif ;">
						<thead>
							<tr>
								<th class="sortablecolumn">Report Title</th>
								<th style="text-align:right" class="sorttable_nosort">Size</th>
								<th class="sortablecolumn">Edition</th>
								<th class="sorttable_nosort">Status</th>
							</tr>
						</thead>
						<tbody>
						<%
							SimpleDateFormat dfmt = new SimpleDateFormat("dd/MM/yy");
							DecimalFormat dfFmt = new DecimalFormat("#,###.#");

							for(int i=0;i<arrDownloads.length;i++){

								int status = arrDownloads[i].getStatus();
								String message = "";
								boolean clickable = false;
								String rowColor = null;
								String cursor = "default";

								switch(status){
									case MerlinUtilities.REPORT_STATUS_IN_PROGRESS:
										message = "Preparing Edition";
										rowColor = "black";
										break;
									case MerlinUtilities.REPORT_STATUS_AVAILABLE:
										clickable = true;
										message = "Click to download";
										rowColor = "#038243";
										cursor = "pointer";
										break;
									case MerlinUtilities.REPORT_STATUS_ALREADY_DOWNLOADED:
										message = "Downloaded on " + dfmt.format(arrDownloads[i].getDownloadDate());
										rowColor = "red";
										break;
								}

								out.print("<tr style='color:" + rowColor + ";cursor:" + cursor + "'" + (clickable?"onclick='downloadReport(\"" + arrDownloads[i].getDownloadUuid() + "\")'":"") + ">");
								out.print("<td>" + arrDownloads[i].getReportTitle() + "</td>");
								out.print("<td style='text-align: right'>" + dfFmt.format(arrDownloads[i].getReportSize()/1048576.0) + "MB</td>");
								out.print("<td>" + arrDownloads[i].getReportEdition() + "</td>");
								out.print("<td>" + message + "</td>");
								out.println("</tr>");

							}
						%>
						</tbody>
					</table>
					<br>Note that report files are large PDF files and may take some minutes to successfully download.
				</td>
			</tr>
			<%
				}
			%>
		</table>

		<%
			if(sectorIds != null && ! sectorIds.equals("")){
		%>
		<script>
			calculatePrice(document.frm);
		</script>
		<%
			}
		%>
		<script>
			sorttable.init();
		</script>
	</BODY>
</HTML>